/*
 * @Description: 校验数据
 * @Author: chenjiaxin
 * @Date: 2021-12-21 21:15:37
 * @LastEditTime: 2022-01-04 21:51:22
 * @FilePath: \novel-serve\src\middleware\check.middleware.js
 */
const errorTypes = require("../constants/error-types");

const paramRequiredCheck = async (ctx, next, isVerifyToken, paramList, query) => {
  try {
    console.log("需要传的字段", paramList);
    // query = JSON.parse(JSON.stringify(query))
    console.log("客户端传了", query);
    // console.log(Object.getPrototypeOf(ctx.request.query));
    if (isVerifyToken) {
      let token = ctx.headers.token || ctx.headers.authorization;
      if (!token) {
        
        return ctx.app.emit("error", errorTypes.NO_TOKEN, ctx, `缺少 token`);
       
      }
    }
    for (let value of paramList) {
      if (!query.hasOwnProperty(value)) { // hasOwnProperty
        console.log(`没有传 ${value}字段`);
        return ctx.app.emit("error", errorTypes.LACK_PARAM, ctx, `缺少 ${value} 字段`);
        
      }
      console.log(value);
    }
    console.log('====await next====');

    await next();
  } catch (error) {
    return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
  }
  
  
}

/**
 * 
 * @param {*} isVerifyToken 是否校验token
 * @param  {...any} args 需要校验的参数名 string
 * @returns 
 */
const paramCheckBody = (isVerifyToken, ...args) => {
  return async (ctx, next) => {
    let query = ctx.request.body;
    await paramRequiredCheck(ctx, next, isVerifyToken, args, query);
    
  }

}

const paramCheckQuery = (isVerifyToken, ...args) => {
  return async (ctx, next) => {
    let query = ctx.request.query;
    //为啥会没有原型
    query = JSON.parse(JSON.stringify(query));
    await paramRequiredCheck(ctx, next, isVerifyToken, args, query);
  }
  
}

module.exports = {
  paramCheckBody,
  paramCheckQuery
};


